package com.bbbug.coree.utils;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class MiscUtil {
    private static final long EXPIRE_TIME = 72*60 * 60 * 1000;//单位：毫秒
    private static final Long mod=10000000000L;
    private static final String TOKEN_SECRET = "BBBUG";
    public static String createToken(String userId) {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            String token = JWT.create()
                    .setPayload("userid", userId)
                    .setKey(TOKEN_SECRET.getBytes(StandardCharsets.UTF_8))
                    .setExpiresAt(date)
                    .sign();
            return token;
    }
    public static String createToken(String userId,Integer second) {

        Date date = new Date(System.currentTimeMillis() + second*1000);
        String token = JWT.create()
                .setPayload("userid", userId)
                .setKey(TOKEN_SECRET.getBytes(StandardCharsets.UTF_8))
                .setExpiresAt(date)
                .sign();
        return token;

    }
    public static String verifyToken(String token){
        try {
            JWT jwt = JWT.of(token);
//            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
//            System.out.println(format.format(new Date(jwt.getPayloads().getLong("exp"))));
            //System.out.println(jwt.getPayloads().getLong("exp")+"---"+System.currentTimeMillis());
            if(jwt.getPayloads().getLong("exp")<=System.currentTimeMillis()){
                return null;
            }
            return jwt.getPayloads().getStr("userid");
        }catch (Exception e){
            return null;
        }

    }
    public static String getres(String key)  {
        key=key.replace(" ","&nbsp");
        String randomString= RandomUtil.randomNumbers(8);
        String url = "http://bd.kuwo.cn/api/www/search/searchMusicBykeyWord?key="+key+"&pn=1&rn=45";
        Map<String,String> header=new HashMap<>();
        header.put("Referer","http://bd.kuwo.cn");
        header.put("csrf",randomString);
        header.put("Cookie","kw_token="+randomString);
        String s="";
        try {
            s=HttpUtil.createGet(url).addHeaders(header).execute().body();
        } catch (Exception e) {

        }
        return s.replace("&nbsp"," ").replace(";("," ");
    }
    public static String getLRC(String key)  {
        String url = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId="+key;
        String randomString= RandomUtil.randomNumbers(8);
        Map<String, String> hashMap = new HashMap();
        hashMap.put("Referer","http://bd.kuwo.cn");
        hashMap.put("csrf",randomString);
        hashMap.put("Cookie","kw_token="+randomString);
        String s="";
        try {
            s = HttpUtil.createGet(url).addHeaders(hashMap).execute().body();
        } catch (Exception e) {

        }
        s=s.replace("&nbsp"," ");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("data",JSON.parseObject(s).getJSONObject("data").getJSONArray("lrclist"));
        jsonObject.put("code",200);
        jsonObject.put("msg","获取成功");

        return jsonObject.toJSONString();
    }
    private final static TemplateEngine templateEngine = new TemplateEngine();

    /**
     * 使用 Thymeleaf 渲染 HTML
     * @param template  HTML模板
     * @param params 参数
     * @return  渲染后的HTML
     */
    public static String render(String template, Map<String, Object> params){
        Context context = new Context();
        context.setVariables(params);
        return templateEngine.process(template, context);
    }
    public static String NextId(){

        return System.currentTimeMillis()/100%mod+""+RandomUtil.randomInt(100000);
    }
    public static boolean testWsdlConnection(String address) {
        int status = 404;
        try {
            URL urlObj = new URL(address);
            HttpURLConnection oc = (HttpURLConnection) urlObj.openConnection();
            oc.setUseCaches(false);
            oc.setConnectTimeout(3000); // 设置超时时间
            status = oc.getResponseCode();// 请求状态
            if (200 == status) {
                // 200是请求地址顺利连通。。
                return true;
            }

        } catch (Exception e) {
            //do nothing
        }

        return false;
    }


}
